import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import hilog from '@ohos.hilog';
const TAG = 'mediaLibrary.ts'
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import { BusinessError } from '@ohos.base';
import bundleManager from '@ohos.bundle.bundleManager';
import featureAbility from '@ohos.ability.featureAbility';
import fs from '@ohos.file.fs';
import util from '@ohos.util';
import common from '@ohos.app.ability.common';


export async function example(context1 : any) {
  console.info('getAssets');
   let permissionRequestResult = await abilityAccessCtrl.createAtManager().requestPermissionsFromUser(context1,
      [
        'ohos.permission.CAMERA',
        'ohos.permission.MICROPHONE',
        'ohos.permission.READ_MEDIA',
        'ohos.permission.WRITE_MEDIA',
        'ohos.permission.MEDIA_LOCATION',
        'ohos.permission.INTERNET',
        'ohos.permission.READ_IMAGEVIDEO'
      ]);
  if (permissionRequestResult.authResults[6] === 0) {
      // 控制相机是否打开
      //AppStorage.SetOrCreate(QRCodeScanConst.HAS_CAMERA_PERMISSION, true)
      //logger.info('MainAbility permissionRequestResult success')
    hilog.info(0x0000, 'testTag', 'getPermissionDef successfully: %{public}s', "JSON.stringify(data)");
    }

  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  //const context =  getContext(context1);
  let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context1);
  /*phAccessHelper.getAssets(fetchOptions, async (err, fetchResult) => {
    if (fetchResult != undefined) {
      console.info('fetchResult success');
      let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
      if (photoAsset != undefined) {
        console.info('photoAsset.displayName : ' + photoAsset.displayName);
      }
    } else {
      console.error('fetchResult fail' + err);
    }
  });*/

  console.info('getAssets');
/*  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };*/
  try {
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
    if (fetchResult != undefined) {
      console.info('fetchResult success');
      let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getLastObject();
      if (photoAsset != undefined) {
        console.info('photoAsset.uri :' + photoAsset.uri);

        photoAsset.getReadOnlyFd((err, fd) => {
          if (fd != undefined) {
            console.info('File fd' + fd);
            let stat = fs.statSync(fd); // 获取文件状态
            let buf = new ArrayBuffer(stat.size); // 创建一个ArrayBuffer对象
            let base64 = new  util.Base64Helper(); // 实例化Base64Helper
            let num = fs.readSync(fd, buf);   // 读取文件
            let data = base64.encodeSync(new Uint8Array(buf.slice(0, num))) //  转换成Uint8Array
            console.info(`data长度:${data.length}`)
            console.info(`data:${data}`)
            let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM : true })
            let retStr = textDecoder.decodeWithStream( data , {stream: false});   // 可以把Uint8Array转码成base64
            //console.info(retStr)
            let base64String = retStr;
            photoAsset.close(fd);
          } else {
            console.error('File err' + err);
          }
        });


        /*let file = fs.openSync(photoAsset.uri, fs.OpenMode.READ_WRITE); // 打开文件

        let stat = fs.statSync(photoAsset.uri); // 获取文件状态
        console.info("stat.size:"+stat.size) // 打印文件的长度
        let buf = new ArrayBuffer(stat.size); // 创建一个ArrayBuffer对象
        let base64 = new  util.Base64Helper(); // 实例化Base64Helper
        let num = fs.readSync(file.fd, buf);   // 读取文件
        let data = base64.encodeSync(new Uint8Array(buf.slice(0, num))) //  转换成Uint8Array
        console.info(`data长度:${data.length}`)
        console.info(`data:${data}`)
        let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM : true })
        let retStr = textDecoder.decodeWithStream( data , {stream: false});   // 可以把Uint8Array转码成base64
        console.info(retStr)*/
      }
    }
  } catch (err) {
    console.error('getAssets failed, message = ', err);
  }
}